package com.cat.dataStructure03;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/longest-non-decreasing-subarray-after-replacing-at-most-one-element/
 * @create 2025/11/9 17:30
 * @since JDK17
 */

class Solution30 {
    public int longestSubarray(int[] nums) {
        int n = nums.length, ans = 2;
        if (n == 1) {
            return 1;
        }
        int[] suf = new int[n];
        suf[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            if (nums[i + 1] >= nums[i]) {
                suf[i] = suf[i + 1] + 1;
            } else {
                suf[i] = 1;
            }
        }
        for (int i = 1, pre = 1; i < n; i++) {
            if (nums[i - 1] <= nums[i + 1]) {
                ans = Math.max(ans, suf[i - 1] + 1 + suf[i + 1]);
            }
            if (nums[i] >= nums[i - 1]) {
                pre++;
                ans = Math.max(ans, pre);
            } else {
                pre = 1;
            }
        }

        return ans;
    }
}
